import { getAvatar, getMobile, getNickname, getUserId, setAccessToken, setAvatar, setMobile, setNickname, setRefreshToken, setUseInfo, setUserId, setUserType } from '@/utils/storage'
import { fetchUserInfo, getPhoneByCode, getUserInfo, login } from '@/apis/login'
import { redirectToHome, sleep } from '@/utils/common'
import store from '@/store'

const user = {
  state: {
    nickname: getNickname(),
    avatar: getAvatar(),
    mobile: getMobile(),
    userId: getUserId(),
  },
  mutations: {
    SET_NICKNAME: (state, payload) => {
      state.nickname = payload
      setNickname(payload)
    },
    SET_AVATAR: (state, payload) => {
      state.avatar = payload
      setAvatar(payload)
    },
    SET_MOBILE: (state, payload) => {
      state.mobile = payload
      setMobile(payload)
    },
    SET_USER_ID: (state, payload) => {
      state.userId = payload
      setUserId(payload)
    },
  },
  actions: {
    async Login({ commit }, code) {
      try {
        if (!code) {
          uni.showToast({ title: '获取手机号失败' })
        } else {
          await uni.showLoading({
            title: '登录中',
            mask: true,
          })

          const res = await login({ grant_type: 'mini_app', code })
          const { access_token, refresh_token, user_info: { id, phone } } = res
          setAccessToken(access_token)
          setRefreshToken(refresh_token)
          setUserId(id)
          commit('SET_MOBILE', phone)
          commit('SET_USER_ID', id)
          const { roles, sysUser: { avatar, nickname } } = await fetchUserInfo()
          commit('SET_NICKNAME', nickname)
          commit('SET_AVATAR', avatar)
          setUserType(roles.includes('3') ? 0 : 1)
          const info = await getUserInfo()
          setUseInfo(info)
          // 获取字典项
          await store.dispatch('dict/loadDictDatas')
          // 如果是员工，请求办公菜单
          if (!roles.includes('3')) {
            await store.dispatch('menu/fetchMenus')
          }

          await uni.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1000,
          })
          uni.login({
            async success(res) {
              if (res.code) {
                // 发起网络请求
                if (getMobile()) {
                  const param = {
                    code: res.code,
                    phone: getMobile(),
                  }
                  await getPhoneByCode(param)
                }
              }
            },
          })
          // hack! 目前暂无方案用于提示信息结束后执行回调，只能使用 sleep
          await sleep(1000)
          redirectToHome()
        }
      } catch (e) {
        console.error(e)
        uni.showToast({
          icon: 'error',
          title: e.message,
        })
      }
    },
  },
}

export default user
